import win32api
import win32con
import serial
import time
import threading
from maLogger import *

maxtimeout = 10

class VirtualKeyboard():
    def __init__(self, *args, **kargs):
        self._logger = maGetLogger('keyboard')
        self.port = serial.Serial()
        self.port.baudrate = 115200
        self.__lkey = 0 #记录按下的键值
        self.__keypressed_timeout = 0 #用于记录按键是否一直被按下
        self.__timout_cnt = 0
        self.port.timeout = 3
        self.serial_task_thread = threading.Thread(name='serial', target=self._serial_task_entry)

    def begin(self, name, baud = 115200):
        self.port.baudrate = baud
        self.port.port = name
        try:
            if not self.port.is_open:
                self.port.open()
                self._logger.info('open port %s success.'%name)
                self.serial_task_thread.start()
                return True
            else:
                self._logger.info('port %s is already open.'%name)
                return True
        except BaseException as e:
            self._logger.error(e)
            return False
    
    def _serial_task_entry(self):
        while(True):
            if self.port.in_waiting>0:
                msg = bytes.decode(self.port.readline())
                self.port.flush()
                if(len(msg)>0):
                    msg = msg[0]
                    nkey = ord(msg)
                    if(self.__lkey != nkey):
                        self.__keypressed_timeout = 0
                    else:
                        self.__keypressed_timeout = maxtimeout
                    self.__lkey = nkey
                    self._logger.debug(msg)
                    self.__timout_cnt = 0
                else:
                    self.__keypressed_timeout = 0
            else:
                self.__timout_cnt += 1
                if(self.__timout_cnt>5):
                    self.__timout_cnt = 0
                    self.__keypressed_timeout = 0
            time.sleep(0.01)

    def pressKey(self, k):
        self.__keypressed_timeout = maxtimeout 
        # if(k==0x53):
        #     k = 0x01 # mouse left button
        win32api.keybd_event(k,0,win32con.KEYEVENTF_EXTENDEDKEY,0)
        while(self.__keypressed_timeout>0):
            self.__keypressed_timeout -= 1
            time.sleep(0.1)
            if(self.__keypressed_timeout<=0):
                break
            win32api.keybd_event(k,0,win32con.KEYEVENTF_EXTENDEDKEY,0)            
        win32api.keybd_event(k,0,win32con.KEYEVENTF_KEYUP,0)
        self.__lkey = 0
        time.sleep(0.05)
    
    def waitKey(self):
        while(True):
            if(self.__lkey>0):
                self.pressKey(self.__lkey)
            time.sleep(0.001)

if __name__ == '__main__':
    initLogger()
    vkd = VirtualKeyboard()
    vkd.begin('COM17')
    vkd.waitKey()